//===============================================================================
// Microsoft patterns & practices
// Mobile Client Software Factory - July 2006
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

#if PocketPC
using Microsoft.Practices.Mobile.TestTools.UnitTesting;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.Practices.Mobile.PinAuthentication.Tests
{
	[TestClass]
	public class ExponentOneKey
	{
		//[TestMethod]
		public void BuildExponentOneKeyAsText()
		{
			byte[] nullKey = BuildExponentOneKey();
			string hex = CryptographyUtility.GetHexStringFromBytes(nullKey);
		}

		//
		// This builds an exponent one null key. This key can be used with CryptExportKey to return
		// the key without being encrypted. For more details, see:
		//
		// http://support.microsoft.com/default.aspx?scid=KB;en-us;q228786
		//
		private byte[] BuildExponentOneKey()
		{
			using (CryptoNativeHelper crypt = new CryptoNativeHelper())
			{
				// Generate and export the private key. We'll convert it to a private exponent of one key.
				byte[] bytes = crypt.GetExchangeKey();

				// Get the bit length of the key (we're assuming it's less than 64K.
				int bitLength = bytes[12] + bytes[13] << 8;

				//
				// Modify the Exponent in Key BLOB format. Key BLOB format is document in SDK.
				// Convert pubexp in rsapubkey to 1.
				//
				bytes[16] = 1;
				bytes[17] = 0;
				bytes[18] = 0;
				bytes[19] = 0;

				// Skip exponent1
				int index = 20;
				index += bitLength / 8;
				index += bitLength / 16;
				index += bitLength / 16;

				// Convert exponent2 to 1
				bytes[index] = 1;
				for (int i = index + 1; i < index + bitLength / 16; i++)
				{
					bytes[i] = 0;
				}

				return bytes;
			}
		}
	}
}
